package com.essence.common.launch;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.boot.SpringApplication;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.ResourceLoader;

import java.io.IOException;
import java.util.function.Function;

public class CryptoLauncher {
    private static Logger logger = LoggerFactory.getLogger(CryptoLauncher.class);

    public static void loadResources(SpringApplication app, String[] cryptos, Function<byte[], byte[]> decryptFunc) throws IOException {
        ResourceLoader resourceLoader = app.getResourceLoader();
        for (String crypto : cryptos) {
            byte[] bytes = resourceLoader.getResource(crypto).getInputStream().readAllBytes();
            byte[] apply = decryptFunc.apply(bytes);
            logger.info("apply crypto:\n{}\n", new String(apply));
            YamlPropertiesFactoryBean yamlPropertiesFactoryBean = new YamlPropertiesFactoryBean();
            yamlPropertiesFactoryBean.setResources(new ByteArrayResource(apply));
            app.setDefaultProperties(yamlPropertiesFactoryBean.getObject());
        }
    }
}
